//
//  GKNovelTabController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2018/9/10.
//  Copyright © 2018 wangws1990. All rights reserved.
//

import UIKit
import AVFoundation
import MBProgressHUD
import AVFoundation
import MediaPlayer
import SwiftyJSON

class GKNovelTabController: BaseViewController{
    convenience init(bookId : String,chapter : Int) {
        self.init()
        self.bookId = bookId
        self.chapter  = chapter
    }
    private var pageCtrl   :UIPageViewController?   = nil
    private var joinedCtrl :UIPageViewController?   = nil
    private var covelCtrl  :DZMCoverController?     = nil
    private var scrollCtrl :GKNovelTableController? = nil
    
    private var book       :GKBook?        = nil
    private var source     :GKSource?      = nil
    private var content    :GKContent?     = nil
    private var listChapter:[JSON]    = []
    
    private var bookId     :String  = ""
    private var chapter    :Int     = 0
    private var pageIndex  :Int     = 0

    private var voiceSlider :UISlider? = nil
    
    private lazy var tapView : GKNovelTapView = {
        let tap  = GKNovelTapView()
        tap.setView.delegate = self
        tap.topView.delegate = self
        tap.bottomView.delegate = self
        tap.directoryView.delegate = self
        return tap
    }()
    private var browse :GKNovelBrowse?{
        return moya.bookSet.browse
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.fd_interactivePopDisabled = true
        self.fd_prefersNavigationBarHidden = true
        self.view.addSubview(self.tapView)
        self.tapView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction(sender:)))
        tap.delegate = self
        self.view.addGestureRecognizer(tap)
        self.loadUI()
        self.loadData(false)
        self.loadFavData()
        self.loadNotification()
        self.setNeedsStatusBarAppearanceUpdate()
    }
    private func loadVoiceCtrl(){
        let session = AVAudioSession.sharedInstance()
        guard let _ = try? session.setCategory(.playback) else { return }
        guard let _ = try? session.setActive(true, options: .notifyOthersOnDeactivation) else { return }
        if let view = self.view.viewWithTag(10000){
            view.removeFromSuperview()
        }
        let volumeView = MPVolumeView(frame: CGRect(x: -120, y: -120, width: 10, height: 10))
        volumeView.isHidden = false;
        self.view.addSubview(volumeView)
        volumeView.tag = 10000
        volumeView.subviews.forEach { item in
            if let slider = item as? UISlider {
                self.voiceSlider = slider
            }
        }
        moya.voiceNumber = session.outputVolume;
    }
    private func loadNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(volumeChangeNotification(sender:)), name:AppVolumeNotication, object: nil)
    }
    @objc func volumeChangeNotification(sender :NSNotification){
        DispatchQueue.main.async {
            if sender.name == AppVolumeNotication{
                guard let newChange = sender.userInfo else { return }
                let json = JSON(newChange)
                guard let model = GKBookVolume.deserialize(from: json.rawString()) else { return }
                if moya.bookSet.browse == .scroll{
                    return
                }
                if !model.userChage{
                    return
                }
                let newKey = model.volume
                if newKey < moya.voiceNumber{
                    self.rightAction(true)
                }
                if newKey > moya.voiceNumber{
                    self.leftAction(true)
                }
                if newKey == moya.voiceNumber{
                    if newKey == 0{
                        self.rightAction(true)
                    }
                    if newKey == 1{
                        self.leftAction(true)
                    }
                }
                moya.voiceNumber = newKey
                if let voiceSlider = self.voiceSlider {
                    if newKey > 0.95{
                        moya.voiceNumber = 0.05
                        voiceSlider.setValue(moya.voiceNumber, animated: false)
                    }
                    if newKey < 0.05{
                        moya.voiceNumber = 0.95
                        voiceSlider.setValue(moya.voiceNumber, animated: false)
                    }
                }
            }
        }
    }
    private func loadUI(){
        switch self.browse {
        case .pageCurl:
            self.loadPageCtrlUI()
            break;
        case .scroll:
            self.loadScrollCtrl()
            break
        case .joined:
            self.loadJoinedCtrl()
            break
        default:
            self.loadCovelCtrlUI()
            break;
        }
    }
    private func reloadUI(){
        self.content?.pageContent()
        switch self.browse {
        case .pageCurl:
            self.reloadPageCtrlUI()
            break;
        case .scroll:
            self.loadScrollCtrlData()
            break
        case .joined:
            self.reloadJoinedCtrlUI()
            break
        default:
            self.reloadCovelCtrlUI()
            break;
        }
        self.reloadDataUI()
        
    }
    @objc private func tapAction(sender:UITapGestureRecognizer){
        let width = self.view.frame.size.width
        let point : CGPoint = sender.location(in:self.view);
        if point.x > width/3.0 && point.x < width/3.0*2 {
            if self.tapView.isHidden  {
                self.tapView.showTapAction()
            }
        }else if point.x < width/3{
            if self.tapView.isHidden  {
                self.leftAction()
            }
        }else if point.x > width/3.0*2{
            if self.tapView.isHidden  {
                self.rightAction()
            }
        }
    }
    private func nextAction(){
        let listData = self.listChapter;
        if self.chapter + 1 >= listData.count {
            MBProgressHUD.showToast("已经是最后一章")
            return;
        }
        self.chapter = self.chapter + 1
        self.pageIndex = 0
        self.bookContent(self.chapter)
    }
    private func lastAction(){
        if self.chapter == 0 {
            MBProgressHUD.showToast("已经是第一章")
            return;
        }
        self.chapter = self.chapter - 1
        self.pageIndex = 0
        self.bookContent(self.chapter)
    }
    private func loadData(_ fromNet :Bool){
        MBProgressHUD.showHUD(self.view, canTap: true, animated: true)
        GKHistoryData.getCacheChapters(bookId: bookId) { model in
            MBProgressHUD.hideHUD(self.view, animated: true)
            guard let item = model,let listChapter = item.chapters else{
                self.loadData(true)
                return
            }
            if listChapter.count == 0{
                self.goOutAction()
                return
            }
            if self.chapter == 0 {
                self.chapter = item.chapter
                self.pageIndex = item.pageIndex
            }
            self.source = item.source
            self.book   = item.book
            self.listChapter = listChapter
            self.bookContent(self.chapter)
            self.reloadData()
        }
    }
    private func loadFavData(){
        let have = GKShelfData.haveData(bookId)
        if have{
            GKShelfData.updateNew(bookId: bookId, newIcon: 0) { success in
                
            }
        }
        self.tapView.topView.favBtn.isSelected = have
    }
    private func reloadData(){
        guard let book = self.book else { return }
        //self.tapView.bottomView.dayBtn.isSelected = moya.bookSet.night;
        self.tapView.topView.titleLab.text = book.title ?? "";
        let have = GKShelfData.haveData(bookId)
        self.tapView.topView.favBtn.isSelected = have
    }
    private func goOutAction(){
        ATAlertView.showAlertView(title: "章节列表获取失败", message: nil, normals: ["重试"], hights: ["退出"]) { title, index in
            if index > 0{
                self.goBack()
            }else{
                self.loadData(true)
            }
        }
    }
    private func bookContent(_ chapter :NSInteger,needHud :Bool = false){
        if self.listChapter.count > chapter{
            MBProgressHUD.showHUD(self.view, canTap: true, animated: true)
            let json = self.listChapter[chapter]
            GKCacheData.getCache(bookId: bookId, json: json) { object in
                MBProgressHUD.hide(for: self.view, animated: true)
                self.content = object
                self.reloadUI()
            } failure: { error in
                MBProgressHUD.hide(for: self.view, animated: true)
                ATAlertView.showAlertView(title: "数据空空如也", message: nil, normals: ["重试"], hights: ["退出"]) { title, index in
                    if index > 0{
                        self.goBack()
                    }else{
                        self.bookContent(chapter)
                    }
                }
            }
        }
    }
    private func removePageCtrlUI(){
        guard let pageCtrl = self.pageCtrl else { return  }
        pageCtrl.view.removeFromSuperview();
        pageCtrl.removeFromParent();
        pageCtrl.dataSource = nil;
        pageCtrl.delegate = nil;
    }
    private func loadPageCtrlUI(){
        self.removePageCtrlUI()
        self.removewCovelCtrlUI()
        self.removeScrollCtrl()
        self.removeJoinedCtrl()
        let vc = GKNovelController()
        self.pageCtrl = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
        guard let pageCtrl = self.pageCtrl else { return  }
        pageCtrl.dataSource = self
        pageCtrl.delegate = self
        pageCtrl.setViewControllers([vc], direction: .forward, animated: false, completion: nil)
        self.addChild(pageCtrl)
        self.view.addSubview(pageCtrl.view)
        self.view.sendSubviewToBack(pageCtrl.view)
        pageCtrl.didMove(toParent: self);
        pageCtrl.view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview();
        }
    }
    private func removewCovelCtrlUI(){
        guard let covelCtrl = self.covelCtrl else { return  }
        covelCtrl.view.removeFromSuperview()
        covelCtrl.removeFromParent()
        covelCtrl.delegate = nil
    }
    private func loadCovelCtrlUI(){
        self.removePageCtrlUI()
        self.removewCovelCtrlUI()
        self.removeScrollCtrl()
        self.removeJoinedCtrl()
        let model = moya.bookSet
        let vc  = GKNovelController()
        self.covelCtrl = DZMCoverController()
        guard let covelCtrl = self.covelCtrl else { return  }
        covelCtrl.setController(vc);
        covelCtrl.delegate = self;
        covelCtrl.openAnimate = (model.browse == .defaults);
        self.addChild(covelCtrl);
        self.view.addSubview(covelCtrl.view);
        self.view.sendSubviewToBack(covelCtrl.view);
        covelCtrl.didMove(toParent: self);
        covelCtrl.view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview();
        }
    }
    private func removeScrollCtrl(){
        guard let scrollCtrl = self.scrollCtrl else { return  }
        scrollCtrl.view.removeFromSuperview()
        scrollCtrl.removeFromParent()
    }
    private func loadScrollCtrl(){
        self.removePageCtrlUI()
        self.removewCovelCtrlUI()
        self.removeScrollCtrl()
        self.removeJoinedCtrl()
        
        self.scrollCtrl = GKNovelTableController()
        self.scrollCtrl?.delegate = self
        guard let scrollCtrl = self.scrollCtrl else { return  }
        self.addChild(scrollCtrl);
        self.view.addSubview(scrollCtrl.view);
        self.view.sendSubviewToBack(scrollCtrl.view);
        scrollCtrl.didMove(toParent: self);
        scrollCtrl.view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview();
        }
    }
    private func removeJoinedCtrl(){
        guard let joinedCtrl = self.joinedCtrl else { return  }
        joinedCtrl.view.removeFromSuperview()
        joinedCtrl.removeFromParent()
    }
    private func loadJoinedCtrl(){
        self.removePageCtrlUI()
        self.removewCovelCtrlUI()
        self.removeScrollCtrl()
        self.removeJoinedCtrl()
        
        let dic = [UIPageViewController.OptionsKey.interPageSpacing : 0]
        let vc = GKNovelController()
        self.joinedCtrl = UIPageViewController(transitionStyle: .scroll, navigationOrientation: .horizontal, options: dic)
        guard let joinedCtrl = self.joinedCtrl else { return  }
        joinedCtrl.dataSource = self
        joinedCtrl.delegate = self
        joinedCtrl.setViewControllers([vc], direction: .forward, animated: false, completion: nil)
        self.addChild(joinedCtrl)
        self.view.addSubview(joinedCtrl.view)
        self.view.sendSubviewToBack(joinedCtrl.view)
        joinedCtrl.didMove(toParent: self);
        joinedCtrl.view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview();
        }
    }
    private func reloadPageCtrlUI(){
        guard let pageCtrl = self.pageCtrl else { return  }
        pageCtrl.setViewControllers([self.readCtrl], direction: .forward, animated: false, completion: nil);
    }
    private func reloadCovelCtrlUI(){
        guard let covelCtrl = self.covelCtrl else { return  }
        covelCtrl.setController(self.readCtrl)
    }
    private func reloadScrollCtrlUI(){
        guard let scrollCtrl = self.scrollCtrl else { return  }
        scrollCtrl.reloadUI()
        self.reloadDataUI()
    }
    private func reloadJoinedCtrlUI(){
        guard let joinedCtrl = self.joinedCtrl else { return  }
        joinedCtrl.setViewControllers([self.readCtrl], direction: .forward, animated: false, completion: nil);
    }
    //数据和UI分离 目录切换阅览
    private func loadScrollCtrlData(){
        guard let scrollCtrl = self.scrollCtrl else { return }
        scrollCtrl.setBook(bookId: bookId, chapter: self.chapter, listChapter: self.listChapter)
        scrollCtrl.reloadUI()
    }
    private func reloadDataUI(){
        self.tapView.content = self.content
        self.tapView.bottomView.slider.value = Float(self.pageIndex)
        self.tapView.directoryView.setDatas(listData: self.listChapter)
        self.tapView.directoryView.chapter = self.listChapter[self.chapter]
    }
    @objc private func buttonAction(){
        self.pageIndex = 0;
        self.bookContent(self.chapter);
    }
    private func leftAction(_ animated :Bool = false){
        guard let beforeCtrl = self.beforeCtrl else { return }
        self.setUpdown()
        switch self.browse {
        case .pageCurl:
            guard let pageCtrl = self.pageCtrl else { return  }
            pageCtrl.setViewControllers([beforeCtrl], direction: .reverse, animated: animated, completion: nil)
            break;
        case .joined:
            guard let joinedCtrl = self.joinedCtrl else { return  }
            joinedCtrl.setViewControllers([beforeCtrl], direction: .reverse, animated: animated, completion: nil)
            break
        case .scroll:
            break
        default:
            guard let covelCtrl = self.covelCtrl else { return  }
            covelCtrl.setController(beforeCtrl)
            break;
        }
    }
    private func rightAction(_ animated :Bool = false){
        guard let afterCtrl = self.afterCtrl else { return }
        self.setUpdown()
        switch self.browse {
        case .pageCurl:
            guard let pageCtrl = self.pageCtrl else { return  }
            pageCtrl.setViewControllers([afterCtrl], direction: .forward, animated: animated, completion: nil)
            break;
        case .joined:
            guard let joinedCtrl = self.joinedCtrl else { return  }
            joinedCtrl.setViewControllers([afterCtrl], direction: .forward, animated: animated, completion: nil)
            break
        case .scroll:
            break
        default:
            guard let covelCtrl = self.covelCtrl else { return  }
            covelCtrl.setController(afterCtrl)
            break;
        }
    }

    private var beforeCtrl :GKNovelController?{
        guard let vc = self.showCtrl else { return nil }
        self.setUpdown()
        if self.pageIndex <= 0 && self.chapter <= 0 {
            self.chapter = 0
            self.pageIndex = 0
            return nil
        }else if(self.pageIndex <= 0){
            if vc.chapter == self.chapter{
                self.chapter  = self.chapter - 1
                self.getNovelContent(chapter: self.chapter)
                guard let content = self.content else { return nil }
                self.pageIndex = content.pageCount - 1
            }
        }else{
            if vc.pageIndex == self.pageIndex{
                self.pageIndex = self.pageIndex - 1
            }
        }
        return self.readCtrl
    }
    private var afterCtrl : GKNovelController?{
        guard let vc = self.showCtrl else { return nil }
        guard let content = self.content else { return nil }
        self.setUpdown()
        if self.pageIndex >= content.pageCount - 1 && self.chapter >= self.listChapter.count {
            return nil
        }else if(self.pageIndex >= content.pageCount - 1){
            if vc.chapter == self.chapter{
                self.chapter = self.chapter + 1
                if self.listChapter.count > self.chapter{
                    self.getNovelContent(chapter: self.chapter)
                    self.pageIndex = 0;
                }else{
                    self.chapter = self.chapter - 1
                    return nil
                }
            }
        }else{
            if(vc.pageIndex == self.pageIndex){
                self.pageIndex = self.pageIndex + 1;
            }
        }
        return self.readCtrl
    }
    private var readCtrl :GKNovelController{
        let vc = GKNovelController()
        vc.delegate = self
        if self.listChapter.count > self.chapter {
            self.getBeforeData()
            self.getAfterData()
            guard let content = self.content else { return vc }
            self.pageIndex = self.pageIndex >= content.pageCount ? content.pageCount - 1 : self.pageIndex
            vc.setModel(model:content, chapter: self.chapter, pageIndex: self.pageIndex);
            self.tapView.bottomView.slider.value = Float(self.pageIndex)
        }
        return vc
    }
    private var showCtrl :GKNovelController?{
        switch self.browse {
        case .pageCurl:
            guard let pageCtrl = self.pageCtrl else { return  nil}
            guard let ctrl = pageCtrl.viewControllers?.first as? GKNovelController else { return nil }
            return ctrl
        case .joined:
            guard let joinedCtrl = self.joinedCtrl else { return  nil}
            guard let ctrl = (joinedCtrl.viewControllers?.first as? GKNovelController) else { return nil }
            return ctrl
        case .defaults,.nones:
            guard let covelCtrl = self.covelCtrl else { return  nil}
            guard let ctrl = (covelCtrl.currentController as? GKNovelController) else { return nil }
            return ctrl
        default:
            break
        }
        return nil
    }
    private func setUpdown(){
        let browse = moya.bookSet.browse
        if browse == .joined {
            if let vc = self.joinedCtrl?.viewControllers?.first as? GKNovelController {
                self.currentCtrl(ctrl: vc)
            }
        }else if browse == .pageCurl{
            if let vc = self.pageCtrl?.viewControllers?.first as? GKNovelController {
                self.currentCtrl(ctrl: vc)
            }
        }
    }
    private func currentCtrl(ctrl:GKNovelController) {
        if self.pageIndex != ctrl.pageIndex {
            self.pageIndex = ctrl.pageIndex
        }
        if self.chapter != ctrl.chapter {
            self.chapter = ctrl.chapter
            self.getNovelContent(chapter: self.chapter)
        }
    }
    private func getBeforeData(){
        let chapter = self.chapter - 1;
        if chapter >= 0 && self.listChapter.count > chapter {
            let chap = self.listChapter[chapter]
            getContent(chap)
        }
    }
    private func getAfterData(){
        guard let content = self.content else { return }
        if content.pageCount > 0 {
            let chapter = self.chapter + 1;
            if content.pageCount > self.pageIndex && self.listChapter.count > chapter {
                let chap = self.listChapter[chapter]
                getContent(chap)
            }
        }
    }
    private func getContent(_ json : JSON){
        let chapterId = json["id"].stringValue
        let contentJson = ApiCache.values(key: chapterId).json
        
        if contentJson.isEmpty && contentJson.count == 0 {
            GKCacheData.getCache(bookId: bookId, json: json) { object in
                if let js = object.toJSON(){
                    ApiCache.set(object: js, key: chapterId)
                }
            } failure: { error in
                
            }
        }
    }
    private lazy var emptyContent: GKContent = {
        let content = GKContent()
        content.pageContent()
        return content
    }()

    private func getNovelContent(chapter :NSInteger){
        if self.listChapter.count > chapter {
            let json  = self.listChapter[chapter]
            guard let info = GKChapter.deserialize(from: json.rawString()) else { return  }
            self.content = info.content
            if info.chapterId.count == 0{
                self.content = self.emptyContent
            }
            self.content?.pageContent()
        }
    }
    private func insertHistoryData(){
        GKHistoryData.updateChap(bookId: bookId, chap: self.chapter, page: self.pageIndex) { success in
            
        }
    }
    func landscapeActon(){
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate{
            self.tapView.tapAction()
            appDelegate.rotation = .landscapeRight
            let value = UIInterfaceOrientation.landscapeRight.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
            UIViewController.attemptRotationToDeviceOrientation()
            self.loadUI()
            self.reloadUI()
        }
    }
    func portraitAction(){
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate{
            self.tapView.tapAction()
            appDelegate.rotation = .portrait
            let value = UIInterfaceOrientation.portrait.rawValue
            UIDevice.current.setValue(value, forKey: "orientation")
            UIViewController.attemptRotationToDeviceOrientation()
            self.loadUI()
            self.reloadUI()
        }
    }
    override var prefersStatusBarHidden: Bool{
        return self.tapView.topView.isHidden ? true : false
    }
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .default
    }
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool{
        if let view = touch.view{
            if view.tag == 10086{
                return false
            }
        }
        return true;
    }
    override var shouldAutorotate: Bool{
        return true
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return [.portrait,.landscapeRight]
    }
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        return .portrait
    }
}
extension GKNovelTabController : GKTopDelegate{
    func topView(topView : GKNovelTopView,back : Bool){
        if moya.landscape{
            self.portraitAction()
        }else{
            self.goBack();
            self.insertHistoryData();
            ApiCache.removeAll()
            ApiMoya.cancelAllRequests()
        }
    }
    func topView(topView : GKNovelTopView,fav  : Bool){
        if !fav {
            GKShelfData.deleteBookModel(bookId:bookId) { (success) in
                topView.favBtn.isSelected = false
            }
        }else{
            guard let model = self.book else { return  }
            GKShelfData.insertBookModel(bookDetail:model) { (success) in
                topView.favBtn.isSelected = true
            }
        }
    }
}
extension GKNovelTabController : GKBookSetDelegate{
    func changeFont(setView: GKBookSetView) {
        self.reloadUI();
    }
    func changeRead(setView: GKBookSetView) {
        self.loadUI()
        self.reloadUI()
    }
    func changeSkin(setView: GKBookSetView) {
        self.reloadUI()
    }
    func changeHalf(setView: GKBookSetView) {
        moya.landscape ? self.portraitAction() : self.landscapeActon()
    }
}
extension GKNovelTabController : GKBottomDelegate{
    func bottomView(bottomView :GKNovelTabView,last   :Bool){
        last ? lastAction() : nextAction();
    }
    func bottomView(bottomView :GKNovelTabView,tabType:GKTabType){
        switch tabType {
        case .set:
            self.tapView.setAction()
            break
        case .mulu:
            self.tapView.showMuluView()
            break
        default:
            self.reloadUI()
            break
        }
    }
    func bottomView(bottomView :GKNovelTabView,slider :Int){
        self.pageIndex = slider
        self.reloadUI()
    }
}
extension GKNovelTabController : GKNovelDirectoryDelegate{
    func selectChapter(view :GKNovelDirectoryView, chapter:NSInteger){
        self.chapter = chapter
        self.pageIndex = 0
        self.bookContent(self.chapter)
        self.tapView.tapAction()
    }
}
extension GKNovelTabController :GKBookDelegate{
    func viewDidAppear(chapter: NSInteger, pageIndex: NSInteger, content: GKContent?) {
        if self.chapter == chapter && self.pageIndex == pageIndex{
            self.insertHistoryData()
            return
        }
        if let con = content{
            self.content = con
        }
        self.chapter = chapter
        self.pageIndex = pageIndex
        self.reloadDataUI()
        self.insertHistoryData()
    }
}
extension GKNovelTabController : DZMCoverControllerDelegate{
    func coverController(_ coverController: DZMCoverController, currentController: UIViewController?, finish isFinish: Bool) {
        if let vc = currentController as?  GKNovelController{
            self.currentCtrl(ctrl:vc)
        }
    }
    func coverController(_ coverController: DZMCoverController, getAboveControllerWithCurrentController currentController: UIViewController?) -> UIViewController? {
        return self.beforeCtrl
    }
    func coverController(_ coverController: DZMCoverController, getBelowControllerWithCurrentController currentController: UIViewController?) -> UIViewController? {
        return self.afterCtrl
    }
}
extension GKNovelTabController : UIPageViewControllerDelegate,UIPageViewControllerDataSource{
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    }
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        return self.beforeCtrl
    }
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        return self.afterCtrl
    }
    func pageViewController(_ pageViewController: UIPageViewController, spineLocationFor orientation: UIInterfaceOrientation) -> UIPageViewController.SpineLocation {
        guard let item = pageViewController.viewControllers?.first else { return .none }
        if self.browse == .pageCurl{
            guard let pageCtrl = self.pageCtrl else { return .none}
            pageCtrl.setViewControllers([item], direction: .forward, animated: true, completion: nil);
        }else if self.browse == .joined{
            guard let joinedCtrl = self.joinedCtrl else { return .none}
            joinedCtrl.setViewControllers([item], direction: .forward, animated: true, completion: nil);
        }
        return .min;
    }
}
